<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\common\model\User;
use app\common\model\UserLevel;
use app\common\model\UserVip;
use app\common\model\UserPointsLog;
use app\common\model\UserSignLog;
use app\common\model\UserViewLog;

class Member extends Base
{
    /**
     * 会员中心首页
     */
    public function index()
    {
        // 获取当前用户
        $userId = $this->user_id;
        if (!$userId) {
            return $this->error('请先登录');
        }

        $user = User::find($userId);
        if (!$user) {
            return $this->error('用户不存在');
        }

        // 获取会员等级信息
        $level = $user->level;

        // 获取下一个等级信息
        $nextLevel = null;
        if ($level) {
            $nextLevel = UserLevel::getNextLevel($level->id);
        }

        // 获取VIP信息
        $vipInfo = $user->getVipInfo();

        // 获取积分统计
        $pointsStats = UserPointsLog::getUserPointsStats($userId);

        // 获取签到信息
        $continuousDays = UserSignLog::getUserContinuousDays($userId);
        $todaySigned    = UserSignLog::checkTodaySigned($userId);

        // 获取浏览统计
        $viewStats = UserViewLog::getUserViewStats($userId);

        // 获取VIP套餐列表
        $vipPackages = UserVip::getEnabledVips();

        // 获取支付网关
        $paymentChannels = (new Pay())->getPayChannelData();

        // 渲染页面
        return $this->success('获取成功', [
            'user'             => $user,
            'level'            => $level,
            'next_level'       => $nextLevel,
            'vip_info'         => $vipInfo,
            'points_stats'     => $pointsStats,
            'continuous_days'  => $continuousDays,
            'today_signed'     => $todaySigned,
            'view_stats'       => $viewStats,
            'vip_packages'     => $vipPackages,
            'payment_channels' => $paymentChannels,
        ]);
    }

    /**
     * 会员等级页面
     */
    public function level()
    {
        // 获取当前用户
        $userId = $this->user_id;
        if (!$userId) {
            return $this->error('请先登录');
        }

        $user = User::find($userId);
        if (!$user) {
            return $this->error('用户不存在');
        }

        // 获取所有会员等级
        $levels = UserLevel::getEnabledLevels();

        // 为每个等级添加权益信息
        foreach ($levels as &$level) {
            $level['benefits'] = $this->getLevelBenefits($level);
        }

        // 获取当前会员等级
        $currentLevel = $user->level;
        if ($currentLevel) {
            $currentLevel             = $currentLevel->toArray();
            $currentLevel['benefits'] = $this->getLevelBenefits($currentLevel);
        }

        // 获取下一个等级信息
        $nextLevel = null;
        if ($currentLevel) {
            $nextLevel = UserLevel::getNextLevel($currentLevel['id']);
            if ($nextLevel) {
                $nextLevel['benefits'] = $this->getLevelBenefits($nextLevel);
            }
        }

        // 渲染页面
        return $this->success('获取成功', [
            'user'          => $user,
            'levels'        => $levels,
            'current_level' => $currentLevel,
            'next_level'    => $nextLevel,
        ]);
    }

    /**
     * VIP会员页面
     */
    public function vip()
    {
        // 获取当前用户
        $userId = $this->user_id;
        if (!$userId) {
            return $this->error('请先登录');
        }

        $user = User::find($userId);
        if (!$user) {
            return $this->error('用户不存在');
        }

        // 获取VIP信息
        $vipInfo = $user->getVipInfo();

        // 获取所有VIP套餐
        $vipPackages = UserVip::getEnabledVips();

        // 获取支付网关
        $paymentChannels = (new Pay())->getPayChannelData();

        // 渲染页面
        return $this->success('获取成功', [
            'user'             => $user,
            'vip_info'         => $vipInfo,
            'vip_packages'     => $vipPackages,
            'payment_channels' => $paymentChannels,
        ]);
    }

    public function buyVip()
    {
        $userId     = $this->user_id;
        $channel_id = $this->request->post('channel_id');
        $vip_id     = $this->request->post('vip_id');
        $trade_no   = UserVip::purchaseVip($userId, $vip_id, $channel_id);
        if ($trade_no) {
            return $this->success('订单创建成功！请及时支付！', $trade_no);
        } else {
            return $this->error('订单创建失败！');
        }
    }

    /**
     * 积分页面
     */
    public function points()
    {
        // 获取当前用户
        $userId = $this->user_id;
        if (!$userId) {
            return $this->error('请先登录');
        }

        $user = User::find($userId);
        if (!$user) {
            return $this->error('用户不存在');
        }

        // 获取积分记录
        $page       = $this->request->post('page', 1);
        $limit      = 10;
        $pointsLogs = UserPointsLog::getUserPointsLogs($userId, '', $page, $limit);

        // 获取积分统计
        $pointsStats = UserPointsLog::getUserPointsStats($userId);

        // 渲染页面
        return $this->success('获取成功', [
            'user'         => $user,
            'points_logs'  => $pointsLogs,
            'points_stats' => $pointsStats,
        ]);
    }

    /**
     * 签到页面
     */
    public function sign()
    {
        // 获取当前用户
        $userId = $this->user_id;
        if (!$userId) {
            return $this->error('请先登录');
        }

        $user = User::find($userId);
        if (!$user) {
            return $this->error('用户不存在');
        }

        // 获取签到记录
        $month    = $this->request->post('month', date('Y-m'));
        $signLogs = UserSignLog::getUserMonthSignLogs($userId, $month);

        // 获取连续签到天数
        $continuousDays = UserSignLog::getUserContinuousDays($userId);

        // 检查今天是否已签到
        $todaySigned = UserSignLog::checkTodaySigned($userId);

        // 获取签到规则
        $signRules = UserSignLog::getSignRules();

        // 增强签到规则数据
        $enhancedSignRules = $this->enhanceSignRules($signRules);

        // 计算签到统计
        $signStats = $this->getSignStats($userId, $month);

        // 计算今日可获得积分
        $todayPoints = $this->calculateTodayPoints($continuousDays, $todaySigned, $signRules, $userId);

        // 生成日历数据
        $calendarData = $this->generateCalendarData($signLogs, $month);

        // 渲染页面
        return $this->success('获取成功', [
            'user'            => $user,
            'sign_logs'       => $signLogs,
            'continuous_days' => $continuousDays,
            'today_signed'    => $todaySigned,
            'sign_rules'      => $enhancedSignRules,
            'month'           => $month,
            'sign_stats'      => $signStats,
            'today_points'    => $todayPoints,
            'calendar_data'   => $calendarData,
        ]);
    }

    /**
     * 执行签到
     */
    public function doSign()
    {
        // 获取当前用户
        $userId = $this->user_id;
        if (!$userId) {
            return $this->error('请先登录');
        }

        $user = User::find($userId);
        if (!$user) {
            return $this->error('用户不存在');
        }

        // 执行签到
        $result = $user->signIn();

        if ($result['code'] == 1) {
            return $this->success($result['msg'], $result['data']);
        } else {
            return $this->error($result['msg']);
        }
    }

    /**
     * 检查用户今天是否已签到
     */
    public function checkSign()
    {
        $userId = $this->user_id;
        if (!$userId) {
            return $this->error('请先登录');
        }
        $user = User::find($userId);
        if (!$user) {
            return $this->error('用户不存在');
        }
        $signStatus  = UserSignLog::checkTodaySigned($userId);
        $todayPoints = UserSignLog::getTodayPoints($userId);
        return $this->success('获取成功', ['signed' => $signStatus, 'points' => $todayPoints]);
    }

    /**
     * 获取等级权益信息
     * @param array $level 等级信息
     * @return array
     */
    private function getLevelBenefits($level)
    {
        $benefits = [];

        // 根据等级名称或积分范围定义不同的权益
        $levelName = strtolower($level['name'] ?? '');
        $minPoints = $level['min_points'] ?? 0;

        // 基础权益（所有等级都有）
        $benefits[] = '基础浏览权限';
        $benefits[] = '评论互动功能';

        // 根据积分范围添加权益
        if ($minPoints >= 100) {
            $benefits[] = '高级内容访问';
            $benefits[] = '优先客服支持';
        }

        if ($minPoints >= 500) {
            $benefits[] = '专属内容推荐';
            $benefits[] = '无广告浏览';
        }

        if ($minPoints >= 1000) {
            $benefits[] = 'VIP专属活动';
            $benefits[] = '积分加成奖励';
        }

        if ($minPoints >= 2000) {
            $benefits[] = '专属客服通道';
            $benefits[] = '内容优先更新';
        }

        if ($minPoints >= 5000) {
            $benefits[] = '终身会员特权';
            $benefits[] = '专属定制服务';
        }

        // 根据等级名称添加特殊权益
        if (strpos($levelName, 'vip') !== false || strpos($levelName, '会员') !== false) {
            $benefits[] = 'VIP专属标识';
        }

        if (strpos($levelName, '钻石') !== false || strpos($levelName, 'diamond') !== false) {
            $benefits[] = '钻石会员专属';
        }

        // 每日浏览限制权益
        if (isset($level['daily_view_limit']) && $level['daily_view_limit'] > 0) {
            $benefits[] = "每日可浏览 {$level['daily_view_limit']} 篇内容";
        } else {
            $benefits[] = '无限制浏览';
        }

        return array_unique($benefits);
    }

    /**
     * 增强签到规则数据
     * @param array $signRules 原始签到规则
     * @return array
     */
    private function enhanceSignRules($signRules)
    {
        $enhanced = [];
        foreach ($signRules as $rule) {
            $enhanced[] = [
                'day'         => $rule['day'],
                'points'      => $rule['points'],
                'description' => "连续签到{$rule['day']}天可获得{$rule['points']}积分",
                'is_bonus'    => $rule['day'] == 7, // 第7天是奖励日
            ];
        }
        return $enhanced;
    }

    /**
     * 获取签到统计数据
     * @param int $userId 用户ID
     * @param string $month 月份
     * @return array
     */
    private function getSignStats($userId, $month)
    {
        $startDate = $month . '-01';
        $endDate   = date('Y-m-t', strtotime($startDate));

        return [
            'total_days'              => UserSignLog::where('user_id', $userId)->count(),
            'month_days'              => UserSignLog::where('user_id', $userId)
                ->where('sign_date', '>=', $startDate)
                ->where('sign_date', '<=', $endDate)
                ->count(),
            'total_points'            => UserSignLog::where('user_id', $userId)->sum('points'),
            'month_points'            => UserSignLog::where('user_id', $userId)
                ->where('sign_date', '>=', $startDate)
                ->where('sign_date', '<=', $endDate)
                ->sum('points'),
            'max_continuous_days'     => UserSignLog::where('user_id', $userId)->max('continuous_days'),
            'current_continuous_days' => UserSignLog::getUserContinuousDays($userId),
        ];
    }

    /**
     * 计算今日可获得积分
     * @param int $continuousDays 当前连续签到天数
     * @param bool $todaySigned 今日是否已签到
     * @param array $signRules 签到规则
     * @param int $userId 用户ID
     * @return int
     */
    private function calculateTodayPoints($continuousDays, $todaySigned, $signRules, $userId)
    {
        if ($todaySigned) {
            // 已签到，返回今日获得的积分
            return UserSignLog::getTodayPoints($userId);
        } else {
            // 未签到，计算签到后可获得的积分
            $nextDay = $continuousDays + 1;
            if ($nextDay > 7) {
                $nextDay = 1; // 超过7天重置为1
            }

            foreach ($signRules as $rule) {
                if ($rule['day'] == $nextDay) {
                    return $rule['points'];
                }
            }

            return 5; // 默认积分
        }
    }

    /**
     * 生成日历数据
     * @param array $signLogs 签到记录
     * @param string $month 月份
     * @return array
     */
    private function generateCalendarData($signLogs, $month)
    {
        $year     = (int) substr($month, 0, 4);
        $monthNum = (int) substr($month, 5, 2);

        // 获取当月第一天是星期几
        $firstDay = date('w', strtotime($month . '-01'));
        // 获取当月天数
        $daysInMonth = date('t', strtotime($month . '-01'));

        // 获取已签到的日期
        $signedDates = [];
        foreach ($signLogs as $log) {
            $signedDates[] = $log['sign_date'];
        }

        // 生成日历数据
        $calendar = [];
        $today    = date('Y-m-d');

        // 填充前面的空白
        for ($i = 0; $i < $firstDay; $i++) {
            $calendar[] = ['date' => null, 'day' => null, 'signed' => false, 'is_today' => false];
        }

        // 填充当月天数
        for ($day = 1; $day <= $daysInMonth; $day++) {
            $dateStr    = sprintf('%04d-%02d-%02d', $year, $monthNum, $day);
            $calendar[] = [
                'date'     => $dateStr,
                'day'      => $day,
                'signed'   => in_array($dateStr, $signedDates),
                'is_today' => $dateStr === $today,
            ];
        }

        return $calendar;
    }
}